<?php
// JANUS config includes
require_once $_SERVER['DOCUMENT_ROOT'] . '/../include/apps/janus/config/config.php';

/**
 * Various Facebook-related functions for JANUS Facebook application
 */
class JanusDb
{
	/**
	 * Returns a database connection identifier
	 */
	public static function getDbConnection()
	{
		$conn = oci_connect($GLOBALS['DATABASE']['USER'], $GLOBALS['DATABASE']['PASSWORD'], $GLOBALS['DATABASE']['CONNECTION']);
		if (!$conn)
		{
			error_log('Failed to connect to the database in getDbConnection() - ' . oci_error() , 0);
		}
		return $conn;
	}
	
	/**
	 * Checks whether the specified Facebook id is present in the database
	 * 
	 * @param unknown_type $dbConn Database connection identifier
	 * @param string $facebookId Facebook id to lookup in the database
	 */
	public static function checkUserExists(&$dbConn, $facebookId)
	{
		$returnNum = 0;
		$stid = oci_parse($dbConn, "select count(*) from JANUS where FACEBOOK_ID = :facebook_id");
		
		if (!$stid)
		{
			error_log('Failed to parse query in checkUserExists() - ' . oci_error() , 0);
			return false;
		}
		
		$bind_lib_id = @oci_bind_by_name($stid, ":facebook_id", $facebookId);
		
		if (!$bind_lib_id)
		{
			error_log('Failed to bind variable in checkUserExists() - ' . oci_error() , 0);
			return false;
		}
		
		$exec = @oci_execute($stid , OCI_DEFAULT);
		
		if (!$exec)
		{
			error_log('Failed to execute statement in checkUserExists() - ' . oci_error() , 0);
			return false;
		}
		
		$result = @oci_fetch_array($stid, OCI_RETURN_NULLS);
		
		if($result !== false)
		{
			switch ($result[0])
			{
				// The user is not registered with the system
				case 0:
					return false;
					break;

				// The user is already registered with the system
				case 1:
					return true;
					break;
					
				// The user is not registered
				default:
					error_log('Unexpected value for count in checkUserExists() - Count = ' . $result[0], 0);
					return false;
					break;
			}
		}

		return false;
	}
}
?>